package server.persistance;

import static server.email.EncodingUtils.decodePath;

import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

import javax.mail.NoSuchProviderException;
import javax.mail.internet.AddressException;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import client.bean.Member;
import client.bean.Plan;
import client.persistance.Adminko;

import com.google.gwt.user.client.Window;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

public class AdminkoImpl extends RemoteServiceServlet implements Adminko {
	private static final SessionFactory sf = HibernateUtil.getSessionFactory();

	List<Plan> plans = new ArrayList<Plan>();

	@Override
	public Plan getPlan() {
		return null;
	}

	@Override
	public void addMember(Member member) {
		Session session = sf.openSession();
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			session.save(member);
			tx.commit();
		} catch (RuntimeException e) {
			if (tx != null) {
				tx.rollback();
			}
			e.printStackTrace();
		} finally {
			session.flush();
			session.close();
		}
	}

	@Override
	public void informMembers(Plan plan) {
		try {
			server.email.EmailHelper.spreadMeetingInformation(plan);
		} catch (AddressException e) {
			e.printStackTrace();
			Window.alert("AddressException");
		} catch (NoSuchProviderException e) {
			e.printStackTrace();
			Window.alert("NoSuchProviderException");
		}
	}

	@Override
	public List<Plan> getPlans() {
		List<Plan> plans = null;
		Session session = sf.openSession();
		try {
			session.beginTransaction();
			plans = session.createQuery("from client.bean.Plan").list();
			// plans = DBUtils.convertToPlans(result);
			session.getTransaction().commit();
		} catch (RuntimeException e) {
			e.printStackTrace();
		} finally {
			session.flush();
			session.close();
		}
		return plans;
	}

	@Override
	public void updatePlans(List<Plan> plans) {
		this.plans = plans;
	}

	@Override
	public String getURLFromUniquePath(String encodedPath) {
		return URLDecoder.decode(decodePath(encodedPath));
	}
}